package com.dm.wallpaper.library.helpers;

import com.dm.wallpaper.library.items.Wallpaper;
import com.dm.wallpaper.library.utils.ImageSize;
import com.dm.wallpaper.library.utils.Log;
import ohos.app.Context;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.media.image.ImageSource;
import ohos.media.image.common.ImageInfo;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class ImageSizeHelp {


    public interface ImageSizeChange {
        void imageSizeChange(int length, ImageSize imageSize);
    }

    public static void imageSize(Context context, Wallpaper wallpaper, ImageSizeChange imageSizeChange) {
        if (wallpaper == null) {
            return;
        }

        EventHandler eventHandler = new EventHandler(EventRunner.getMainEventRunner());

        TaskDispatcher globalTaskDispatcher = context.getGlobalTaskDispatcher(TaskPriority.DEFAULT);
        globalTaskDispatcher.syncDispatch(() -> {
            try {
                Thread.sleep(1);
                URL url = new URL(wallpaper.getUrl());
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setConnectTimeout(10000);
                if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    InputStream stream = connection.getInputStream();
                    ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
                    ImageSource imageSource = ImageSource.create(stream, sourceOptions);
                    ImageInfo imageInfo = imageSource.getImageInfo();
                    int width = imageInfo.size.width;
                    int height = imageInfo.size.height;
                    ImageSize imageSize = new ImageSize(width,height);
                    int contentLength = connection.getContentLength();
                    stream.close();
                    eventHandler.postTask(() -> imageSizeChange.imageSizeChange(contentLength, imageSize));
                }
            } catch (Exception e) {
                Log.e("hh", e.getMessage());
            }
        });

    }
}
